// 企业用户
<template>
  <el-form
    :model="ruleForm2"
    status-icon
    :rules="rules"
    ref="ruleForm2"
    label-width="100px"
    class="demo-ruleForm"
  >
    <el-form-item label="用户名" prop="name">
      <el-input type="text" v-model="ruleForm2.name" auto-complete="off" placeholder="请输入用户名/邮箱"></el-input>
    </el-form-item>

    <el-form-item label="密码" prop="pass">
      <el-input type="password" v-model="ruleForm2.pass" auto-complete="off" placeholder="请输入密码"></el-input>
    </el-form-item>

    <el-form-item label="确认密码" prop="checkPass">
      <el-input
        type="password"
        v-model="ruleForm2.checkPass"
        auto-complete="off"
        placeholder="请再次输入密码"
      ></el-input>
    </el-form-item>

    <el-form-item label="手机号码" prop="tel">
      <el-input v-model.number="ruleForm2.tel" placeholder="请输入手机号"></el-input>
    </el-form-item>

    <el-form-item label="验证码" prop="code">
      <div class="code">
        <el-input placeholder="请输入验证码" v-model="ruleForm2.code"></el-input>
        <el-button @click="codeinfor" :disabled="disabling">
          {{ codetexts }}
          <span v-show="showS">s</span>
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="公司名称" prop="companyName">
      <el-input
        type="text"
        v-model="ruleForm2.companyName"
        auto-complete="off"
        placeholder="请输入公司名称"
      ></el-input>
    </el-form-item>

    <el-form-item label="公司性质" prop="companyNature">
      <el-select v-model="ruleForm2.companyNature.name" placeholder="请选择公司性质">
        <el-option
          v-for="item in ruleForm2.companyNature"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="所属行业" prop="industry">
      <el-select v-model="ruleForm2.industry.name" placeholder="请选择所属行业">
        <el-option
          v-for="item in ruleForm2.industry"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        ></el-option>
      </el-select>
    </el-form-item>

    <el-form-item label="营业执照" prop="businessLicense">
      <el-upload
        action
        :auto-upload="false"
        list-type="picture-card"
        ref="upload1"
        :limit="1"
        :on-progress="base64"
        :on-exceed="onExceed"
        accept="image/jpeg, image/jpg, image/png"
        :on-preview="handlePictureCardPreview"
        :on-remove="handleRemove"
      >
        <i class="el-icon-plus"></i>
      </el-upload>
      <p class="tips" style="color: #f40; font-size:12px; text-algin:left">*上传图片不得超过2M</p>
      <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt>
      </el-dialog>

      <p style="font-size：12px;color:#9d9d9d">无营业执照请上传相关证明（支持：jpg,jpeg,png格式图片）</p>
    </el-form-item>

    <el-form-item>
      <el-checkbox v-model="checked1" @change="change">企业用户开票抬头必须和营业执照保持一致</el-checkbox>
    </el-form-item>

    <el-form-item>
      <el-checkbox v-model="checked2" @change="change">了解并同意《孚地卖场用户服务协议》</el-checkbox>

      <el-button type="text" @click="dialogTableVisible = true">>>协议详情</el-button>
    </el-form-item>

    <el-form-item>
      <el-button
        class="register"
        type="primary"
        style="width:412px;margin-left:70px"
        @click="gotoRegister('ruleForm2')"
        :disabled="!disabled"
      >注册</el-button>
    </el-form-item>
    <p class="jumplogin" @click="jumpLogin">
      已有账户?
      <span>去登录 >></span>
    </p>
    <fu-agreement :dialogTableVisible="dialogTableVisible" @cancel="cancel"></fu-agreement>
  </el-form>
</template>
<script>
import FuAgreement from "./FuAgreement"
export default {
  data() {
    let checkAge = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号码不能为空"))
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"))
        } else {
          if (value.length < 11) {
            callback(new Error("手机号码位数缺失"))
          } else {
            callback()
          }
        }
      }, 1000)
    }

    let validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"))
      } else {
        if (this.ruleForm2.checkPass !== "") {
          this.$refs.ruleForm2.validateField("checkPass")
        }
        callback()
      }
    }

    let validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"))
      } else if (value !== this.ruleForm2.pass) {
        callback(new Error("两次输入密码不一致!"))
      } else {
        callback()
      }
    }

    return {
      dialogTableVisible: false, // 弹出框的开关
      disabled: false, // 防止按钮重复提交的状态
      disabling: true, //发送验证码按钮是否能够点击
      showS: 0, // s 时候显示
      btn: "点击按钮进行验证", //
      codetexts: "发送短信验证码", //
      checked1: 0,
      checked2: 0,
      dialogImageUrl: "",
      dialogVisible: false,
      // businessLicense : '',   // 营业执照

      ruleForm2: {
        name: "",
        pass: "",
        checkPass: "",
        tel: "",
        code: "", // 验证码
        companyName: "", // 公司名称
        companyNature: [], //公司性质
        traders: "", //是否贸易商
        industry: [], //所属行业
        businessLicense: "" // base64 营业执照
      },
      rules: {
        name: [
          {
            required: true,
            message: "请输入用户名/邮箱",
            trigger: "blur"
          },
          {
            min: 5,
            max: 18,
            message: "长度在 5 到 18 个字符",
            trigger: "blur"
          }
        ],
        pass: [
          {
            required: true,
            message: "请输入密码",
            trigger: "blur"
          },
          {
            min: 6,
            max: 16,
            message: "长度在 6 到 16 个字符",
            trigger: "blur"
          }
        ],
        checkPass: [
          {
            required: true,
            message: "请确认密码",
            trigger: "blur"
          },
          {
            validator: validatePass2,
            trigger: "blur"
          }
        ],
        tel: [
          {
            validator: checkAge,
            required: true,
            message: "请输入正确的电话号码",
            trigger: "blur"
          }
        ],
        code: [
          {
            required: true,
            message: "验证码不能为空",
            trigger: "blur"
          },
          {
            min: 6,
            max: 6,
            message: "请输入6位验证码",
            trigger: "blur"
          }
        ],
        companyName: [
          {
            required: true,
            message: "请输入公司名称",
            trigger: "blur"
          },
          {
            min: 2,
            message: "请输入正确的公司名称",
            trigger: "blur"
          }
        ],
        // companyNature : [
        //     {
        //         // required: true,
        //         message: '请选择公司性质',
        //         trigger: 'blur'
        //     }
        // ],
        traders: [
          {
            required: true,
            message: "请选择是否贸易商",
            trigger: "blur"
          }
        ],
        // industry: [
        //   {
        //     required: true,
        //     message: "请选择所属行业",
        //     trigger: "blur"
        //   }
        // ],
        businessLicense: [
          {
            required: true,
            message: "请上传营业执照",
            trigger: "blur"
          }
        ],
        realName: [
          {
            required: true,
            message: "请输入真实姓名",
            trigger: "blur"
          },
          {
            min: 3,
            max: 6,
            message: "长度在 3 到 6 个字符",
            trigger: "blur"
          }
        ],
        position: [
          {
            required: true,
            message: "请选择部门职位",
            trigger: "blur"
          }
        ]
      }
    }
  },

  components: {
    FuAgreement
  },

  methods: {
    // 父子组件传值
    cancel(event) {
      this.dialogTableVisible = false
    },
    // check 事件
    change() {
      if (this.checked1 && this.checked2) {
        this.disabled = true
      } else {
        this.disabled = false
      }
    },

    // 数据初始化
    httpInit() {
      this.$http
        .post("index/common/getNature")
        .then(res => {
          let reqdata = res.data
          if (reqdata.State.Code == 200) {
            this.ruleForm2.companyNature = Array.from(reqdata.data)
          }
        })
        .catch(err => {
          console.log("getNature 出错")
        })

      this.$http
        .post("index/common/getIndustry")
        .then(res => {
          let reqdata = res.data
          if (reqdata.State.Code == 200) {
            this.ruleForm2.industry = Array.from(reqdata.data)
          }
        })
        .catch(err => {
          console.log("getIndustry 出错")
        })
    },

    // 图片超过限定数量的钩子函数
    onExceed(files, fileList) {
      this.$message({
        message: "温馨提示:上传图片最多为一张 请勿重复点击...",
        type: "warning"
      })
    },

    // 图片格式转换方法
    base64() {
      let url = document.getElementsByClassName('el-upload-list__item-thumbnail')[0].src
      this.ruleForm2.businessLicense = this.imgbase64(url)
    },
    
    // 转到登录页面
    jumpLogin() {
      const jwt = localStorage.getItem("token")
      if (jwt) {
        this.$notify.info({
          title: "您已登录",
          message: "请勿重复登录3秒后,自动转到首页"
        })
        setTimeout(() => {
          this.$router.push({
            name: "home"
          })
        }, 3000)
      } else {
        this.$router.push({
          name: "login"
        })
      }
    },

    // 删除上传的图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },

    // 图片预览营业执照
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },

    // 短信验证码
    codeinfor() {
      let phone = parseInt(this.ruleForm2.tel)
      console.log(phone)
      try {
        this.$http({
          method: "post",
          url: `index/common/sendMsg`,
          headers: { "X-Requested-With": "XMLHttpRequest" }, // 必须加这个请求头 否则报错：500
          data: {
            phone,
            code: `SMS_143540005`
          }
        })
          .then(res => {
            let _data = res.data
            console.log(_data)
          })
          .catch(err => {
            console.log("出错了请检查代码")
          })
      } catch (error) {
        console.log("账户注册 短信验证码出现问题...")
      }

      this.codetexts = 60 // 60秒
      this.showS = true // s 显示出来
      this.disabling = true // 按钮不能够点击
      let timer = setInterval(() => {
        this.codetexts = this.codetexts - 1
        if (this.codetexts == 0) {
          clearInterval(timer)
          this.codetexts = "请重新发送短信验证码"
          this.showS = false
          this.disabling = false
        }
      }, 1000)
    },

    // 注册接口

    gotoRegister(ruleForm2) {
      this.$refs[ruleForm2].validate((valid) => {
        if (valid) {

          this.base64()
          let param = {
            username: this.ruleForm2.name, // 用户名
            password: this.ruleForm2.pass, //密码
            name: this.ruleForm2.companyName, //公司名称
            nature_id: this.ruleForm2.companyNature.name, //公司性质
            industry_id: this.ruleForm2.industry.name, //所属行业
            phone: this.ruleForm2.tel, //手机号
            license: this.ruleForm2.businessLicense // 营业执照
          }

          let smscode = this.ruleForm2.code

          console.log(param)
          try {
            this.$http({
              method: "post",
              url: `index/register/register`,
              // headers: {'X-Requested-With': 'XMLHttpRequest'},    // 必须加这个请求头 否则报错：500
              data: {
                param,
                smscode,
                code: "company"
              }
            })
              .then(res => {
                let _data = res.data
                console.log(res.data)
                if (_data.State.Code == 200) {
                  console.log(_data) // 成功时候的数据
                  this.disabled = false
                  this.$notify({
                    title: "恭喜...",
                    message: "成功注册了孚地卖场的会员...",
                    type: "success"
                  })
                  this.$router.push({
                    name: "login"
                  })
                } else if (_data.State.Code == 800) {
                  this.$notify.error({
                    title: "验证码错误...",
                    position: 'bottom-right'
                  })
                } else if (_data.State.Code == 1200) {
                  this.$notify.error({
                    title: "手机号已被注册为个人用户...",
                    position: 'bottom-right'
                  })
                } else if (_data.State.Code == 1600) {
                  this.$notify({
                    title: "验证码已经过期...",
                    message: "请重新获取验证码...",
                    type: "warning",
                    position: 'bottom-right'
                  })
                } else if (_data.State.Code == 1800) {
                  this.$notify.error({
                    title: "手机号已被注册企业用户...",
                    position: 'bottom-right'
                  })
                }
              })
              .catch(err => {
                console.log("出错了请检查代码")
              })
          } catch (error) {
            console.log("账户注册接口出现问题...")
          }


        } else {
            console.log('error submit!!')
            return false
        }
      })
 
    }
  },
  watch: {
    ruleForm2: {
      handler(newName, oldName) {
        // console.log(newName, oldName)
        if (newName.tel) {
          this.disabling = false
        }
      },
      deep: true,
      // immediate: true
    }
  },
  mounted() {
    this.httpInit()
  }
}
</script>
<style lang="scss" scoped>
.el-form {
  padding-bottom: 60px;
  .el-form-item {
    .code {
      display: flex;
      flex-direction: row;
      .el-input {
        width: 60%;
      }
      .el-button {
        margin-left: 5px;
      }
      .register {
        width: 412px;
      }
    }
  }
  .jumplogin {
    text-align: right;
    padding-right: 138px;
    span {
      color: #ff7200;
      cursor: pointer;
    }
  }
}
</style>
